<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 via-white to-indigo-50">
    <!-- 顶部导航 -->
    <div class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-10">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-2xl font-bold text-gray-900">我的作文</h1>
            <p class="text-sm text-gray-500 mt-1">
              共 {{ pagination.total }} 篇作文
              <span v-if="completedCount > 0"> · {{ completedCount }} 篇已批改</span>
            </p>
          </div>
          
          <button
            @click="goToSubmit"
            class="inline-flex items-center space-x-2 px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors"
          >
            <PlusCircle class="w-5 h-5" />
            <span>提交新作文</span>
          </button>
        </div>
      </div>
    </div>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 过滤条 -->
      <FilterBar
        @filter-change="handleFilterChange"
        @sort-change="handleSortChange"
        @search="handleSearch"
      />
      
      <!-- 加载骨架屏 -->
      <div v-if="loading" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div
          v-for="i in 6"
          :key="i"
          class="bg-white rounded-lg shadow-sm p-6 animate-pulse"
        >
          <div class="h-6 bg-gray-200 rounded w-3/4 mb-4"></div>
          <div class="h-4 bg-gray-200 rounded w-full mb-2"></div>
          <div class="h-4 bg-gray-200 rounded w-5/6 mb-2"></div>
          <div class="h-4 bg-gray-200 rounded w-4/6"></div>
        </div>
      </div>
      
      <!-- 错误状态 -->
      <div v-else-if="error" class="text-center py-20">
        <AlertCircle class="w-16 h-16 text-red-500 mx-auto mb-4" />
        <h3 class="text-lg font-medium text-gray-900 mb-2">加载失败</h3>
        <p class="text-gray-600 mb-4">{{ error }}</p>
        <button
          @click="loadEssays"
          class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors"
        >
          重新加载
        </button>
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="!hasEssays" class="text-center py-20">
        <FileText class="w-20 h-20 text-gray-400 mx-auto mb-4" />
        <h3 class="text-xl font-medium text-gray-900 mb-2">
          {{ hasFilters ? '没有找到符合条件的作文' : '还没有作文' }}
        </h3>
        <p class="text-gray-600 mb-6">
          {{ hasFilters ? '试试调整筛选条件' : '快来提交你的第一篇作文吧！' }}
        </p>
        <button
          v-if="!hasFilters"
          @click="goToSubmit"
          class="inline-flex items-center space-x-2 px-6 py-3 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors"
        >
          <PlusCircle class="w-5 h-5" />
          <span>提交新作文</span>
        </button>
        <button
          v-else
          @click="clearFilters"
          class="px-6 py-3 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition-colors"
        >
          清除筛选
        </button>
      </div>
      
      <!-- 作文列表 -->
      <div v-else>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
          <EssayCard
            v-for="essay in displayEssays"
            :key="essay.id"
            :essay="essay"
            @view="handleView"
            @edit="handleEdit"
            @submit="handleSubmit"
          />
        </div>
        
        <!-- 分页 -->
        <div v-if="pagination.total > pagination.limit" class="bg-white rounded-lg shadow-sm p-6">
          <div class="flex items-center justify-between">
            <!-- 分页信息 -->
            <div class="text-sm text-gray-600">
              显示第 {{ startIndex }} - {{ endIndex }} 项，共 {{ pagination.total }} 项
            </div>
            
            <!-- 分页按钮 -->
            <div class="flex items-center space-x-2">
              <button
                @click="prevPage"
                :disabled="currentPage === 1"
                class="px-4 py-2 text-sm font-medium border border-gray-300 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                :class="[
                  currentPage === 1
                    ? 'bg-gray-100 text-gray-400'
                    : 'bg-white text-gray-700 hover:bg-gray-50'
                ]"
              >
                <ChevronLeft class="w-4 h-4" />
              </button>
              
              <!-- 页码 -->
              <div class="flex items-center space-x-1">
                <button
                  v-for="page in visiblePages"
                  :key="page"
                  @click="goToPage(page)"
                  class="w-10 h-10 text-sm font-medium rounded-lg transition-colors"
                  :class="[
                    currentPage === page
                      ? 'bg-blue-500 text-white'
                      : 'bg-white text-gray-700 hover:bg-gray-50 border border-gray-300'
                  ]"
                >
                  {{ page }}
                </button>
              </div>
              
              <button
                @click="nextPage"
                :disabled="currentPage === totalPages"
                class="px-4 py-2 text-sm font-medium border border-gray-300 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                :class="[
                  currentPage === totalPages
                    ? 'bg-gray-100 text-gray-400'
                    : 'bg-white text-gray-700 hover:bg-gray-50'
                ]"
              >
                <ChevronRight class="w-4 h-4" />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { 
  PlusCircle, 
  AlertCircle, 
  FileText,
  ChevronLeft,
  ChevronRight
} from 'lucide-vue-next';
import { useEssayStore } from '../stores/essay.js';
import FilterBar from '../components/FilterBar.vue';
import EssayCard from '../components/EssayCard.vue';

/**
 * HistoryPage 组件
 * 显示用户的作文批改历史列表
 */

// ==================== Composition API ====================
const router = useRouter();
const essayStore = useEssayStore();

// ==================== Refs ====================
const loading = ref(true);
const error = ref(null);
const currentPage = ref(1);
const filters = ref({});
const sortBy = ref('newest');
const searchQuery = ref('');

// ==================== Computed ====================

/**
 * 作文列表
 */
const essays = computed(() => essayStore.essays);

/**
 * 分页信息
 */
const pagination = computed(() => essayStore.pagination);

/**
 * 是否有作文
 */
const hasEssays = computed(() => essays.value.length > 0);

/**
 * 是否有过滤条件
 */
const hasFilters = computed(() => {
  return Object.keys(filters.value).length > 0 || searchQuery.value !== '';
});

/**
 * 已完成作文数量
 */
const completedCount = computed(() => {
  return essays.value.filter(e => e.status === 'completed').length;
});

/**
 * 总页数
 */
const totalPages = computed(() => {
  return Math.ceil(pagination.value.total / pagination.value.limit);
});

/**
 * 当前页起始索引
 */
const startIndex = computed(() => {
  return (currentPage.value - 1) * pagination.value.limit + 1;
});

/**
 * 当前页结束索引
 */
const endIndex = computed(() => {
  return Math.min(
    currentPage.value * pagination.value.limit,
    pagination.value.total
  );
});

/**
 * 可见的页码
 */
const visiblePages = computed(() => {
  const pages = [];
  const maxVisible = 5;
  const total = totalPages.value;
  
  if (total <= maxVisible) {
    for (let i = 1; i <= total; i++) {
      pages.push(i);
    }
  } else {
    const current = currentPage.value;
    const half = Math.floor(maxVisible / 2);
    
    let start = Math.max(1, current - half);
    let end = Math.min(total, current + half);
    
    if (current <= half) {
      end = maxVisible;
    }
    
    if (current >= total - half) {
      start = total - maxVisible + 1;
    }
    
    for (let i = start; i <= end; i++) {
      pages.push(i);
    }
  }
  
  return pages;
});

/**
 * 显示的作文列表（应用搜索过滤）
 */
const displayEssays = computed(() => {
  let result = essays.value;
  
  // 客户端搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(essay => 
      essay.title?.toLowerCase().includes(query) || 
      essay.content?.toLowerCase().includes(query)
    );
  }
  
  // 客户端排序
  if (sortBy.value === 'newest') {
    result = [...result].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
  } else if (sortBy.value === 'oldest') {
    result = [...result].sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
  } else if (sortBy.value === 'score-high') {
    result = [...result].sort((a, b) => (b.score || 0) - (a.score || 0));
  } else if (sortBy.value === 'score-low') {
    result = [...result].sort((a, b) => (a.score || 0) - (b.score || 0));
  }
  
  return result;
});

// ==================== Methods ====================

/**
 * 加载作文列表
 */
const loadEssays = async (resetPage = false) => {
  loading.value = true;
  error.value = null;
  
  if (resetPage) {
    currentPage.value = 1;
  }
  
  try {
    const params = {
      limit: pagination.value.limit,
      offset: (currentPage.value - 1) * pagination.value.limit,
      ...filters.value,
    };
    
    await essayStore.fetchEssays(params);
  } catch (err) {
    error.value = err.message || '加载作文列表失败';
    console.error('[HistoryPage] Load essays failed:', err);
  } finally {
    loading.value = false;
  }
};

/**
 * 处理过滤变化
 */
const handleFilterChange = (newFilters) => {
  filters.value = newFilters;
  loadEssays(true);
};

/**
 * 处理排序变化
 */
const handleSortChange = (newSort) => {
  sortBy.value = newSort;
  // 客户端排序，不需要重新加载
};

/**
 * 处理搜索
 */
const handleSearch = (query) => {
  searchQuery.value = query;
  // 客户端搜索，不需要重新加载
};

/**
 * 清除过滤条件
 */
const clearFilters = () => {
  filters.value = {};
  sortBy.value = 'newest';
  searchQuery.value = '';
  loadEssays(true);
};

/**
 * 上一页
 */
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    loadEssays();
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }
};

/**
 * 下一页
 */
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    loadEssays();
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }
};

/**
 * 跳转到指定页
 */
const goToPage = (page) => {
  if (page !== currentPage.value) {
    currentPage.value = page;
    loadEssays();
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }
};

/**
 * 跳转到提交页面
 */
const goToSubmit = () => {
  router.push('/submit');
};

/**
 * 查看作文
 */
const handleView = (essay) => {
  console.log('[HistoryPage] View essay:', essay.id);
};

/**
 * 编辑作文
 */
const handleEdit = (essay) => {
  console.log('[HistoryPage] Edit essay:', essay.id);
};

/**
 * 提交批改
 */
const handleSubmit = (essay) => {
  console.log('[HistoryPage] Submit essay:', essay.id);
  // 重新加载列表以更新状态
  setTimeout(() => {
    loadEssays();
  }, 1000);
};

// ==================== Lifecycle ====================

onMounted(() => {
  loadEssays();
});
</script>

<style scoped>
/* 骨架屏动画 */
@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

.animate-pulse {
  animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
</style>

